package util

import (
	model "carmanager/models"
	"fmt"
	"time"

	"github.com/golang-jwt/jwt/v4"
)

const (
	SECRETKEY = "243223ffslsfsldfl412fdsfsdf" //私钥
)

type UserClaims struct {
	UserId   int64
	Role     int
	NickName string
	jwt.StandardClaims
	user model.User
}

func GenToken(user *model.User) (error, string) {

	// 创建Token结构体
	claims := jwt.NewWithClaims(jwt.SigningMethodHS256, UserClaims{
		NickName: user.UserName,
		UserId:   int64(user.ID),
		Role:     user.Roleid,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(time.Duration(60*60*24) * time.Second).Unix(), // 过期时间，必须设置
			Issuer:    "jerry",                                                      // 非必须，也可以填充用户名，
		},
	})
	// 调用加密方法，发挥Token字符串
	signingString, err := claims.SignedString([]byte(SECRETKEY))
	if err != nil {
		return err, ""
	}
	return nil, signingString
}

func PaserToken(tokenString string) (*UserClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(SECRETKEY), nil
	})
	if claims, ok := token.Claims.(*UserClaims); ok && token.Valid {
		return claims, nil
	} else {
		return nil, err
	}
}
